CKEDITOR.dialog.add('galleryDialogMain', function(editor){
    var lang = editor.lang.gallery;
    var defaultWidth  = 200;
    var defaultHeight = 150;
    var defaultAlign  = 'right';

    return {
        title:     lang.photoGallery,
        minWidth:  400,
        minHeight: 400,
        resizable: CKEDITOR.DIALOG_RESIZE_NONE,

        buttons: [
            CKEDITOR.dialog.cancelButton,
            CKEDITOR.dialog.okButton
        ],

        contents: [
            {
                id: 'galleryInfo',
                label: lang.settings,
                align : 'center',
                elements: [
                    {
                        type: 'hbox',
                        widths: ['33%', '33%', '33%'],
                        children: [
                            {
                                type: 'text',
                                id:   'width',
                                label: lang.width+':',
                                'default': defaultWidth,
                                setup: function(element) {
                                    this.setValue(element.getAttribute('width'));
                                }
                            },
                            {
                                type: 'text',
                                id:   'height',
                                label: lang.height+':',
                                'default': defaultHeight,
                                setup: function(element) {
                                    this.setValue(element.getAttribute('height'));
                                }
                            },
                            {
                                type: 'select',
                                id:   'align',
                                label: lang.align+':',
                                items: [[lang.dontAlign, ''], [lang.left, 'left'], [lang.right, 'right']],
                                'default': defaultAlign,
                                setup: function(element) {
                                    this.setValue(element.getAttribute('align'));
                                }
                            }
                        ]
                    },
                    {
                        type: 'hbox',
                        widths: ['0%', '50%', '50%'],
                        id: 'galleryItem',
                        children: [
                            {
                                type:  'text',
                                id:    'imagePickTxt',
                                style: 'display:none',
                                onChange: function() {
                                    var url = this.getValue();
                                    var dialog = this.getDialog();
                                    var ul = getImageList(dialog);

                                    addImageIntoList(dialog, ul, url);
                                }
                            },
                            {
                                type:  'button',
                                id:    'imagePick',
                                label: lang.addImage,
                                filebrowser: {
                                    action: 'Browse',
                                    target: 'galleryInfo:imagePickTxt',
                                    url: editor.config.filebrowserImageBrowseUrl || editor.config.filebrowserBrowseUrl
                                }
                            },
                            {
                                type: 'button',
                                id:   'imageRemove',
                                label: lang.removeImage,
                                style: 'display:none',
                                onClick: function() {
                                    var dialog = this.getDialog();
                                    var ul = getImageList(dialog);
                                    var li = ul.findOne('.selected');
                                    if (li) {
                                        li.remove();
                                        this.getElement().hide();
                                    }
                                }
                            }
                        ]
                    },{
                        type: 'text',
                        id:   'imageListPlaceholder'
                    }
                ]
            }
        ],

        onShow: function(e) {
            var selection = editor.getSelection();
            this.element  = selection.getStartElement();

            galleryAdminUI(this, editor);
            var ul = getImageList(this);
            ul.setHtml('');
            
            // insertMode
            if (!this.element || !this.element.hasClass('photo-gallery')) {
                this.insertMode = true;
                this.element    = null;

            // updateMode
            } else {
                this.insertMode = false;
                this.setupContent(this.element);

                // other attrs are updated automatically
                // we only need to update images here
                var images = this.element.data('images').split(',');
                for (var i=0; i<images.length; i++) {
                    addImageIntoList(this, ul, images[i]);
                }
            }

            
        },

        onOk: function(e) {
            var width  = this.getValueOf('galleryInfo', 'width');
            var height = this.getValueOf('galleryInfo', 'height');
            var align  = this.getValueOf('galleryInfo', 'align');
            var images = [];
            var ul     = getImageList(this);
            var lis    = ul.find('li');
            for (var i=0; i<lis.count(); i++) {
                images.push(lis.getItem(i).data('url'));
            }
            
            var fakeImage = createFakeElement(editor, {
                element: editor.document.createElement('div'),
                images: images,
                width:  width,
                height: height,
                align:  align
            });
            if (!this.element) {
                editor.insertElement(fakeImage);
            } else {
                fakeImage.replace(this.element);
                editor.getSelection().selectElement(fakeImage);
            }
        }
    }
});

function galleryAdminUI(dialog, editor) {
    var placeholder = dialog
                        .getContentElement('galleryInfo', 'imageListPlaceholder')
                        .getElement();
    var container   = placeholder.getParent();
    
    if (container.find('.gallery-image-list').count() < 1) {
        var el = createElement('ul');
        el.addClass('gallery-image-list');
        el.setStyles({
            float: 'left',
            margin: '10px'
        });

        placeholder.insertBeforeMe(el)
        placeholder.hide();
    }
}
function createElement(name, html, style) {
    var el = new CKEDITOR.dom.element(name);
    if (html) {
        el.setHtml(html);
    }
    if (style) {
        el.setStyles(style);
    }

    return el;
}
function getImageList(dialog) {
    return dialog
            .getContentElement('galleryInfo', 'imageListPlaceholder')
            .getElement()
            .getPrevious();
}
function addImageIntoList(dialog, ul, url) {
    var btnRemove = dialog.getContentElement('galleryInfo', 'imageRemove');
    
    var html = '<img src="'+url+'" style="height:50px">';
    var li = createElement('li', html, {
        float:     'left',
        listStyle: 'none',
        margin:    '0 5px 5px 0'
    });
    
    li.data('url', url);
    li.data('btn-remove-id', btnRemove.domId);
    li.on('click', function(){
        var ul  = this.getParent();
        var lis = ul.find('li');
        var btnRemove = document.getElementById(this.data('btn-remove-id'));

        var selected = this.hasClass('selected');

        for (var i=0; i<lis.count(); i++) {
            lis.getItem(i).removeClass('selected');
        }

        if (selected) {
            this.removeClass('selected');
            btnRemove.style.display = 'none';
        } else {
            this.addClass('selected');
            btnRemove.style.display = 'inline-block';
        }
    });
    ul.append(li);
}